package com.code.wordhelper.utils;

import org.apache.poi.wp.usermodel.HeaderFooterType;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.xmlbeans.impl.xb.xmlschema.SpaceAttribute;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFldChar;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTText;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STFldCharType;

import java.util.List;
import java.util.Map;

public class PageNumUtils {
    public static void replaceFoots(XWPFDocument document, Map<String, Object> dataMap) throws Exception {
        List<XWPFFooter> footerList = document.getFooterList();
        for (int i = 0; i < footerList.size(); i++) {
            XWPFFooter footer = footerList.get(i);
            footer.clearHeaderFooter();
        }

        XWPFFooter footer = document.createFooter(HeaderFooterType.DEFAULT);//创建一个新的XWPFFooter对象
        XWPFParagraph paragraph = footer.createParagraph();
        paragraph.setAlignment(ParagraphAlignment.CENTER);
        XWPFRun runPre = paragraph.createRun();
        runPre.setText("第 ");

        XWPFRun run = paragraph.createRun();
        CTFldChar fldChar = run.getCTR().addNewFldChar();
        fldChar.setFldCharType(STFldCharType.Enum.forString("begin"));

        CTText ctText = run.getCTR().addNewInstrText();
        ctText.setStringValue("PAGE  \\* MERGEFORMAT");
        ctText.setSpace(SpaceAttribute.Space.Enum.forString("preserve"));

        fldChar = run.getCTR().addNewFldChar();
        fldChar.setFldCharType(STFldCharType.Enum.forString("end"));

        XWPFRun runMid = paragraph.createRun();
        runMid.setText("页/共 ");

        XWPFRun run2 = paragraph.createRun();
        CTFldChar fldChar2 = run2.getCTR().addNewFldChar();
        fldChar2.setFldCharType(STFldCharType.Enum.forString("begin"));

        CTText ctText2 = run2.getCTR().addNewInstrText();
        ctText2.setStringValue("SECTIONPAGES  \\* MERGEFORMAT");
        ctText2.setSpace(SpaceAttribute.Space.Enum.forString("preserve"));

        fldChar2 = run2.getCTR().addNewFldChar();
        fldChar2.setFldCharType(STFldCharType.Enum.forString("end"));

        XWPFRun runSuf = paragraph.createRun();
        runSuf.setText("页");
    }
}
